<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/yuwanzi.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/yuwanzi.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/yuwanzi.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/yuwanzi.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/yuwanzi.io/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"suyuhuan.gitee.io","root":"/yuwanzi.io/","images":"/yuwanzi.io/images","scheme":"Muse","version":"8.2.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Suche...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}};
  </script>
<meta name="description" content="介绍&amp;nbsp;&amp;nbsp;ActiveMQ 是Apache出品，最流行的，能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。 主要特点：  多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Per">
<meta property="og:type" content="article">
<meta property="og:title" content="ActiveMQ消息队列">
<meta property="og:url" content="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/03/2016-07-03-activemq/index.html">
<meta property="og:site_name" content="玉丸子 | Blog">
<meta property="og:description" content="介绍&amp;nbsp;&amp;nbsp;ActiveMQ 是Apache出品，最流行的，能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。 主要特点：  多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Per">
<meta property="og:locale">
<meta property="og:image" content="http://ww1.sinaimg.cn/mw690/63503acbjw1f67ojz4j8kj20bk03djrj.jpg">
<meta property="og:image" content="http://ww2.sinaimg.cn/mw690/63503acbjw1f67ojyj0g8j20mf0fdwft.jpg">
<meta property="article:published_time" content="2016-07-03T10:00:00.000Z">
<meta property="article:modified_time" content="2020-11-07T00:58:17.000Z">
<meta property="article:author" content="玉丸子">
<meta property="article:tag" content="ActiveMQ">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/mw690/63503acbjw1f67ojz4j8kj20bk03djrj.jpg">


<link rel="canonical" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/03/2016-07-03-activemq/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh'
  };
</script>
<title>ActiveMQ消息队列 | 玉丸子 | Blog</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/yuwanzi.io/atom.xml" title="玉丸子 | Blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Navigationsleiste an/ausschalten" role="button">
    </div>
  </div>

  <div class="site-meta">

    <a href="/yuwanzi.io/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">玉丸子 | Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>







</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Inhaltsverzeichnis
        </li>
        <li class="sidebar-nav-overview">
          Übersicht
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFJMS%E8%A7%84%E8%8C%83"><span class="nav-number">2.</span> <span class="nav-text">什么是JMS规范</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JMS%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E6%8E%A5%E5%8F%A3"><span class="nav-number">3.</span> <span class="nav-text">JMS应用程序接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JMS%E6%B6%88%E6%81%AF%E5%8F%91%E9%80%81%E6%A8%A1%E5%BC%8F"><span class="nav-number">4.</span> <span class="nav-text">JMS消息发送模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85ActiveMQ"><span class="nav-number">5.</span> <span class="nav-text">安装ActiveMQ</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8ActiveMQ"><span class="nav-number">6.</span> <span class="nav-text">使用ActiveMQ</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-Producer"><span class="nav-number">6.1.</span> <span class="nav-text">1.Producer</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-Consumer"><span class="nav-number">6.2.</span> <span class="nav-text">2.Consumer</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B4%E5%90%88Spring"><span class="nav-number">7.</span> <span class="nav-text">整合Spring</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E9%85%8D%E7%BD%AEConnectionFactory"><span class="nav-number">7.1.</span> <span class="nav-text">1.配置ConnectionFactory</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E9%85%8D%E7%BD%AE%E7%94%9F%E4%BA%A7%E8%80%85"><span class="nav-number">7.2.</span> <span class="nav-text">2.配置生产者</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-%E5%8F%91%E9%80%81%E6%B6%88%E6%81%AF"><span class="nav-number">7.3.</span> <span class="nav-text">3.发送消息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-%E9%85%8D%E7%BD%AE%E6%B6%88%E8%B4%B9%E8%80%85"><span class="nav-number">7.4.</span> <span class="nav-text">4.配置消费者</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Exception"><span class="nav-number">8.</span> <span class="nav-text">Exception</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">玉丸子</p>
  <div class="site-description" itemprop="description">这里是玉丸子的个人博客,与你一起发现更大的世界。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/yuwanzi.io/archives">
          <span class="site-state-item-count">68</span>
          <span class="site-state-item-name">Artikel</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/yuwanzi.io/categories/">
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">Kategorien</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/yuwanzi.io/tags/">
        <span class="site-state-item-count">46</span>
        <span class="site-state-item-name">schlagwörter</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh">
    <link itemprop="mainEntityOfPage" href="https://suyuhuan.gitee.io/yuwanzi.io/2016/07/03/2016-07-03-activemq/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/yuwanzi.io/images/avatar.gif">
      <meta itemprop="name" content="玉丸子">
      <meta itemprop="description" content="这里是玉丸子的个人博客,与你一起发现更大的世界。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="玉丸子 | Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ActiveMQ消息队列
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Veröffentlicht am</span>

      <time title="Erstellt: 2016-07-03 18:00:00" itemprop="dateCreated datePublished" datetime="2016-07-03T18:00:00+08:00">2016-07-03</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">Bearbeitet am</span>
        <time title="Geändert am: 2020-11-07 08:58:17" itemprop="dateModified" datetime="2020-11-07T08:58:17+08:00">2020-11-07</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">in</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">后端</span></a>
        </span>
          . 
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/yuwanzi.io/categories/%E5%90%8E%E7%AB%AF/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/" itemprop="url" rel="index"><span itemprop="name">消息队列</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p><img src="http://ww1.sinaimg.cn/mw690/63503acbjw1f67ojz4j8kj20bk03djrj.jpg"></p>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>&nbsp;&nbsp;ActiveMQ 是Apache出品，最流行的，能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。</p>
<p>主要特点：</p>
<ol>
<li>多种语言和协议编写客户端。语言: Java, C, C++, C#, Ruby, Perl, Python, PHP。应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP</li>
<li>完全支持JMS1.1和J2EE 1.4规范 (持久化,XA消息,事务)</li>
<li>对Spring的支持,ActiveMQ可以很容易内嵌到使用Spring的系统里面去,而且也支持Spring2.0的特性</li>
<li>通过了常见J2EE服务器(如 Geronimo,JBoss 4, GlassFish,WebLogic)的测试,其中通过JCA 1.5 resource adaptors的配置,可以让ActiveMQ可以自动的部署到任何兼容J2EE 1.4 商业服务器上</li>
<li>支持多种传送协议:in-VM,TCP,SSL,NIO,UDP,JGroups,JXTA</li>
<li>支持通过JDBC和journal提供高速的消息持久化</li>
<li>从设计上保证了高性能的集群,客户端-服务器,点对点</li>
<li>支持Ajax</li>
<li>支持与Axis的整合</li>
<li>可以很容易得调用内嵌JMS provider,进行测试</li>
</ol>
<h3 id="什么是JMS规范"><a href="#什么是JMS规范" class="headerlink" title="什么是JMS规范"></a>什么是JMS规范</h3><p>&nbsp;&nbsp;JMS的全称是Java MessageService，即Java消息服务。用于在两个应用程序之间，或分布式系统中发送消息，进行异步通信。<br>&nbsp;&nbsp;它主要用于在生产者和消费者之间进行消息传递，生产者负责产生消息，而消费者负责接收消息。把它应用到实际的业务需求中的话我们可以在特定的时候利用生产者生成一消息，并进行发送，对应的消费者在接收到对应的消息后去完成对应的业务逻辑。<br>&nbsp;&nbsp;对于消息的传递有两种类型：<br>一种是点对点的，即一个生产者和一个消费者一一对应；<br>另一种是发布/订阅模式，即一个生产者产生消息并进行发送后，可以由多个消费者进行接收。<br>JMS定义了五种不同的消息正文格式，以及调用的消息类型，允许你发送并接收以一些不同形式的数据，提供现有消息格式的一些级别的兼容性。</p>
<ul>
<li>StreamMessage – Java原始值的数据流</li>
<li>MapMessage–一套名称-值对</li>
<li>TextMessage–一个字符串对象</li>
<li>ObjectMessage–一个序列化的 Java对象</li>
<li>BytesMessage–一个字节的数据流</li>
</ul>
<h3 id="JMS应用程序接口"><a href="#JMS应用程序接口" class="headerlink" title="JMS应用程序接口"></a>JMS应用程序接口</h3><p>&nbsp;&nbsp;<strong>ConnectionFactory</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;用户用来创建到JMS提供者的连接的被管对象。JMS客户通过可移植的接口访问连接，这样当下层的实现改变时，代码不需要进行修改。 管理员在JNDI名字空间中配置连接工厂，这样，JMS客户才能够查找到它们。根据消息类型的不同，用户将使用队列连接工厂，或者主题连接工厂。</p>
<p>&nbsp;&nbsp;<strong>Connection</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;连接代表了应用程序和消息服务器之间的通信链路。在获得了连接工厂后，就可以创建一个与JMS提供者的连接。根据不同的连接类型，连接允许用户创建会话，以发送和接收队列和主题到目标。</p>
<p>&nbsp;&nbsp;<strong>Destination</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;目标是一个包装了消息目标标识符的被管对象，消息目标是指消息发布和接收的地点，或者是队列，或者是主题。JMS管理员创建这些对象，然后用户通过JNDI发现它们。和连接工厂一样，管理员可以创建两种类型的目标，点对点模型的队列，以及发布者／订阅者模型的主题。</p>
<p>&nbsp;&nbsp;<strong>MessageProducer</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;由会话创建的对象，用于发送消息到目标。用户可以创建某个目标的发送者，也可以创建一个通用的发送者，在发送消息时指定目标。</p>
<p>&nbsp;&nbsp;<strong>MessageConsumer</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;由会话创建的对象，用于接收发送到目标的消息。消费者可以同步地（阻塞模式），或异步（非阻塞）接收队列和主题类型的消息。</p>
<p>&nbsp;&nbsp;<strong>Message</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;是在消费者和生产者之间传送的对象，也就是说从一个应用程序创送到另一个应用程序。一个消息有三个主要部分：</p>
<ul>
<li>消息头（必须）：包含用于识别和为消息寻找路由的操作设置。</li>
<li>一组消息属性（可选）：包含额外的属性，支持其他提供者和用户的兼容。可以创建定制的字段和过滤器（消息选择器）。</li>
<li>一个消息体（可选）：允许用户创建五种类型的消息（文本消息，映射消息，字节消息，流消息和对象消息）。</li>
</ul>
<p>消息接口非常灵活，并提供了许多方式来定制消息的内容。</p>
<p>&nbsp;&nbsp;<strong>Session</strong></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;表示一个单线程的上下文，用于发送和接收消息。由于会话是单线程的，所以消息是连续的，就是说消息是按照发送的顺序一个一个接收的。会话的好处是它支持事务。如果用户选择了事务支持，会话上下文将保存一组消息，直到事务被提交才发送这些消息。在提交事务之前，用户可以使用回滚操作取消这些消息。一个会话允许用户创建消息生产者来发送消息，创建消息消费者来接收消息。</p>
<h3 id="JMS消息发送模式"><a href="#JMS消息发送模式" class="headerlink" title="JMS消息发送模式"></a>JMS消息发送模式</h3><p><img src="http://ww2.sinaimg.cn/mw690/63503acbjw1f67ojyj0g8j20mf0fdwft.jpg"></p>
<p>&nbsp;&nbsp;在P2P模型下，一个生产者向一个特定的队列发布消息，一个消费者从该队列中读取消息。这里，生产者知道消费者的队列，并直接将消息发送到消费者的队列。这种模式被概括为：只有一个消费者将获得消息。生产者不需要在接收者消费该消息期间处于运行状态，接收者也同样不需要在消息发送时处于运行状态。每一个成功处理的消息都由接收者签收。</p>
<p>&nbsp;&nbsp;publish/subscribe模型支持向一个特定的消息主题发布消息。0或多个订阅者可能对接收来自特定消息主题的消息感兴趣。在这种模型下，发布者和订阅者彼此不知道对方。这种模式好比是匿名公告板。这种模式被概括为：多个消费者可以获得消息.在发布者和订阅者之间存在时间依赖性。发布者需要建立一个订阅（subscription），以便客户能够购订阅。订阅者必须保持持续的活动状态以接收消息，除非订阅者建立了持久的订阅。在那种情况下，在订阅者未连接时发布的消息将在订阅者重新连接时重新发布。</p>
<h3 id="安装ActiveMQ"><a href="#安装ActiveMQ" class="headerlink" title="安装ActiveMQ"></a>安装ActiveMQ</h3><ol>
<li><p>首先到官网 <a target="_blank" rel="noopener" href="http://activemq.apache.org/">http://activemq.apache.org/</a> 下载ActiveMQ.</p>
</li>
<li><p>因为ActiveMQ是JAVA开发的,所以依赖jdk环境。</p>
</li>
<li><p>解压ActiveMQ。</p>
</li>
<li><p>在ActiveMQ/bin目录中,./activemq start 开启ActiveMQ</p>
</li>
<li><p>在ActiveMQ/bin目录中,./activemq stop 关闭ActiveMQ</p>
</li>
<li><p>访问后台 <a target="_blank" rel="noopener" href="http://ip:8161/admin">http://ip:8161/admin</a>  ActiveMQ的默认后台端口为8161,Message端口为61616</p>
</li>
</ol>
<h3 id="使用ActiveMQ"><a href="#使用ActiveMQ" class="headerlink" title="使用ActiveMQ"></a>使用ActiveMQ</h3><p>&nbsp;&nbsp;使用ActiveMQ需要先引入ActiveMQ的jar包。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">       &lt;dependency&gt;</span><br><span class="line">	&lt;groupId&gt;org.apache.activemq&lt;&#x2F;groupId&gt;</span><br><span class="line">	&lt;artifactId&gt;activemq-all&lt;&#x2F;artifactId&gt;</span><br><span class="line">	&lt;version&gt;5.11.2&lt;&#x2F;version&gt;</span><br><span class="line">&lt;&#x2F;dependency&gt;</span><br></pre></td></tr></table></figure>
<p>以下示例使用Queue模式,如要使用Topic模式只需要将Destination改成Topic即可。</p>
<h4 id="1-Producer"><a href="#1-Producer" class="headerlink" title="1.Producer"></a>1.Producer</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">   <span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testProducer</span><span class="params">()</span> <span class="keyword">throws</span> JMSException</span>&#123;</span><br><span class="line">	<span class="comment">// 创建连接工厂</span></span><br><span class="line">	ConnectionFactory connectionFactory = </span><br><span class="line">				<span class="keyword">new</span> ActiveMQConnectionFactory(<span class="string">&quot;tcp://192.168.145.137:61616&quot;</span>);</span><br><span class="line">	<span class="comment">// 声明Connection</span></span><br><span class="line">	Connection connection = <span class="keyword">null</span>;</span><br><span class="line">	<span class="comment">// 声明Session</span></span><br><span class="line">	Session session = <span class="keyword">null</span>;</span><br><span class="line">	<span class="comment">// 声明Producer</span></span><br><span class="line">	MessageProducer producer = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span>&#123;</span><br><span class="line">		<span class="comment">// 从连接工厂中获得连接</span></span><br><span class="line">		connection = connectionFactory.createConnection();</span><br><span class="line">		<span class="comment">// 开启连接</span></span><br><span class="line">		connection.start();</span><br><span class="line">		<span class="comment">/*</span></span><br><span class="line"><span class="comment">		 * 从连接中获得会话</span></span><br><span class="line"><span class="comment">		 * 参数1:transacted  boolean型</span></span><br><span class="line"><span class="comment">		 * 当设置为true时,将忽略参数2,acknowledgment mode被jms服务器设置 SESSION_TRANSACTED。</span></span><br><span class="line"><span class="comment">		 * 当一个事务被提交时,消息确认就会自动发生。</span></span><br><span class="line"><span class="comment">		 * 当设置为false时,需要设置参数2</span></span><br><span class="line"><span class="comment">		 * Session.AUTO_ACKNOWLEDGE为自动确认，当客户成功的从receive方法返回的时候，或者从</span></span><br><span class="line"><span class="comment">		 * MessageListener.onMessage方法成功返回的时候，会话自动确认客户收到的消息。</span></span><br><span class="line"><span class="comment">		 * Session.CLIENT_ACKNOWLEDGE 为客户端确认。客户端接收到消息后，必须调用javax.jms.Message的</span></span><br><span class="line"><span class="comment">		 * acknowledge方法。jms服务器才会删除消息。（默认是批量确认）</span></span><br><span class="line"><span class="comment">		 */</span></span><br><span class="line">		session = connection.createSession(<span class="keyword">false</span>,Session.AUTO_ACKNOWLEDGE);</span><br><span class="line">		<span class="comment">// 创建一个Destination目的地 Queue或者Topic</span></span><br><span class="line">		Queue queue = session.createQueue(<span class="string">&quot;testMessage&quot;</span>);</span><br><span class="line">		<span class="comment">// 创建一个Producer生产者</span></span><br><span class="line">		producer = session.createProducer(queue);</span><br><span class="line">		<span class="comment">// 创建message</span></span><br><span class="line">		ActiveMQTextMessage textMessage = <span class="keyword">new</span> ActiveMQTextMessage();</span><br><span class="line">		textMessage.setText(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">		<span class="comment">// 发送message</span></span><br><span class="line">		producer.send(textMessage);</span><br><span class="line">	&#125;<span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">		<span class="comment">// 回收资源</span></span><br><span class="line">		producer.close();</span><br><span class="line">		session.close();</span><br><span class="line">		connection.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="2-Consumer"><a href="#2-Consumer" class="headerlink" title="2.Consumer"></a>2.Consumer</h4><p>&nbsp;&nbsp;消费者有两种消费方式:</p>
<ol>
<li><p>同步消费。通过调用消费者的receive方法从目的地中显式提取消息。receive方法可以一直阻塞到消息到达。</p>
</li>
<li><p>异步消费。客户可以为消费者注册一个消息监听器，以定义在消息到达时所采取的动作。<br>  实现MessageListener接口，在MessageListener（）方法中实现消息的处理逻辑。</p>
</li>
</ol>
<p>同步消费</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSyncConsumer</span><span class="params">()</span> <span class="keyword">throws</span> JMSException</span>&#123;</span><br><span class="line">	<span class="comment">// 创建连接工厂</span></span><br><span class="line">	ConnectionFactory connectionFactory = </span><br><span class="line">					<span class="keyword">new</span> ActiveMQConnectionFactory(<span class="string">&quot;tcp://192.168.145.137:61616&quot;</span>);</span><br><span class="line">	Connection connection = <span class="keyword">null</span>;</span><br><span class="line">	Session session = <span class="keyword">null</span>;</span><br><span class="line">	MessageConsumer consumer = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span>&#123;</span><br><span class="line">		<span class="comment">// 获得连接</span></span><br><span class="line">		connection = connectionFactory.createConnection();</span><br><span class="line">		<span class="comment">// 开启连接</span></span><br><span class="line">		connection.start();</span><br><span class="line">		<span class="comment">// 获得Session</span></span><br><span class="line">		session = connection.createSession(<span class="keyword">false</span>,Session.AUTO_ACKNOWLEDGE);</span><br><span class="line">		<span class="comment">// 创建一个目的地</span></span><br><span class="line">		Queue queue = session.createQueue(<span class="string">&quot;testSynchronization&quot;</span>);</span><br><span class="line">		<span class="comment">// 创建消费者</span></span><br><span class="line">		consumer = session.createConsumer(queue);</span><br><span class="line">		<span class="comment">// 使用receive同步消费</span></span><br><span class="line">		<span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</span><br><span class="line">			<span class="comment">// 设置接收信息的时间,单位为毫秒</span></span><br><span class="line">			Message message = consumer.receive(<span class="number">10000</span>);</span><br><span class="line">			<span class="keyword">if</span>(message != <span class="keyword">null</span>)&#123;</span><br><span class="line">				System.out.println(message);</span><br><span class="line">			&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">				<span class="comment">// 超时,结束循环</span></span><br><span class="line">				<span class="keyword">break</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;<span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">		<span class="comment">// 回收资源</span></span><br><span class="line">		consumer.close();</span><br><span class="line">		session.close();</span><br><span class="line">		connection.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>异步消费</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line">   <span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testAsyncConsumer</span><span class="params">()</span> <span class="keyword">throws</span> JMSException</span>&#123;</span><br><span class="line">	<span class="comment">// 创建连接工厂</span></span><br><span class="line">	ConnectionFactory connectionFactory = </span><br><span class="line">				<span class="keyword">new</span> ActiveMQConnectionFactory(<span class="string">&quot;tcp://192.168.145.137:61616&quot;</span>);</span><br><span class="line">	Connection connection = <span class="keyword">null</span>;</span><br><span class="line">	Session session = <span class="keyword">null</span>;</span><br><span class="line">	MessageConsumer consumer = <span class="keyword">null</span>;</span><br><span class="line">	<span class="keyword">try</span>&#123;</span><br><span class="line">		<span class="comment">// 获得连接</span></span><br><span class="line">		connection = connectionFactory.createConnection();</span><br><span class="line">		<span class="comment">// 开启连接</span></span><br><span class="line">		connection.start();</span><br><span class="line">		<span class="comment">// 获得Session</span></span><br><span class="line">		session = connection.createSession(<span class="keyword">false</span>,Session.AUTO_ACKNOWLEDGE);</span><br><span class="line">		<span class="comment">// 设置目的地</span></span><br><span class="line">		Queue queue = session.createQueue(<span class="string">&quot;testAsynchronization&quot;</span>);</span><br><span class="line">		<span class="comment">// 创建Consumer</span></span><br><span class="line">		consumer = session.createConsumer(queue);</span><br><span class="line">		<span class="comment">// 异步消费</span></span><br><span class="line">		session.setMessageListener(<span class="keyword">new</span> MessageListener() &#123;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onMessage</span><span class="params">(Message message)</span> </span>&#123;</span><br><span class="line">				<span class="keyword">if</span>(message <span class="keyword">instanceof</span> TextMessage)&#123;</span><br><span class="line">					<span class="keyword">try</span> &#123;</span><br><span class="line">						String text = ((TextMessage) message).getText();</span><br><span class="line">						System.out.println(text);</span><br><span class="line">					&#125; <span class="keyword">catch</span> (JMSException e) &#123;</span><br><span class="line">						e.printStackTrace();</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">		System.in.read();</span><br><span class="line">	&#125;<span class="keyword">catch</span>(Exception e)&#123;</span><br><span class="line">		e.printStackTrace();</span><br><span class="line">	&#125;<span class="keyword">finally</span>&#123;</span><br><span class="line">		<span class="comment">// 回收资源</span></span><br><span class="line">		consumer.close();</span><br><span class="line">		session.close();</span><br><span class="line">		connection.close();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="整合Spring"><a href="#整合Spring" class="headerlink" title="整合Spring"></a>整合Spring</h3><h4 id="1-配置ConnectionFactory"><a href="#1-配置ConnectionFactory" class="headerlink" title="1.配置ConnectionFactory"></a>1.配置ConnectionFactory</h4><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span><br><span class="line">&lt;beans xmlns=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span><br><span class="line">	xmlns:context=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span> xmlns:p=<span class="string">&quot;http://www.springframework.org/schema/p&quot;</span></span><br><span class="line">	xmlns:aop=<span class="string">&quot;http://www.springframework.org/schema/aop&quot;</span> xmlns:tx=<span class="string">&quot;http://www.springframework.org/schema/tx&quot;</span></span><br><span class="line">	xmlns:jms=<span class="string">&quot;http://www.springframework.org/schema/jms&quot;</span> xmlns:xsi=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="line">	xsi:schemaLocation=<span class="string">&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</span></span><br><span class="line"><span class="string">	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd</span></span><br><span class="line"><span class="string">	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd </span></span><br><span class="line"><span class="string">	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd</span></span><br><span class="line"><span class="string">	http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-4.0.xsd</span></span><br><span class="line"><span class="string">	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd&quot;</span>&gt;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	&lt;!-- ActiveMQ提供的ConnectionFactory --&gt;</span><br><span class="line">	&lt;bean id=<span class="string">&quot;targetConnectionFactory&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;</span>&gt;</span><br><span class="line">		&lt;property name=<span class="string">&quot;brokerURL&quot;</span> value=<span class="string">&quot;tcp://192.168.145.137:61616&quot;</span> /&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	&lt;!-- Spring的ConnectionFactory需要注入ActiveMQ的ConnectionFactory --&gt;</span><br><span class="line">	&lt;bean id=<span class="string">&quot;connectionFactory&quot;</span></span><br><span class="line">		<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.springframework.jms.connection.SingleConnectionFactory&quot;</span>&gt;</span><br><span class="line">		&lt;!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory --&gt;</span><br><span class="line">		&lt;property name=<span class="string">&quot;targetConnectionFactory&quot;</span> ref=<span class="string">&quot;targetConnectionFactory&quot;</span> /&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure>
<h4 id="2-配置生产者"><a href="#2-配置生产者" class="headerlink" title="2.配置生产者"></a>2.配置生产者</h4><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">   &lt;!-- 配置生产者 --&gt;</span><br><span class="line">&lt;!-- Spring提供的JMS工具类，它可以进行消息发送、接收等 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;jmsTemplate&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.springframework.jms.core.JmsTemplate&quot;</span>&gt;</span><br><span class="line">	&lt;!-- 注入Spring的连接工厂 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;connectionFactory&quot;</span> ref=<span class="string">&quot;connectionFactory&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!--P2P模式的Destination --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;queueDestination&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.command.ActiveMQQueue&quot;</span>&gt;</span><br><span class="line">	&lt;constructor-arg&gt;</span><br><span class="line">		&lt;value&gt;queue&lt;/value&gt;</span><br><span class="line">	&lt;/constructor-arg&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!-- publish/subscribe模式的Destination --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;topicDestination&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.command.ActiveMQTopic&quot;</span>&gt;</span><br><span class="line">	&lt;constructor-arg value=<span class="string">&quot;topic&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<h4 id="3-发送消息"><a href="#3-发送消息" class="headerlink" title="3.发送消息"></a>3.发送消息</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSend</span><span class="params">()</span></span>&#123;</span><br><span class="line">		<span class="comment">// 读取Spring配置文件</span></span><br><span class="line">		ApplicationContext applicationContext = </span><br><span class="line">					<span class="keyword">new</span> ClassPathXmlApplicationContext(<span class="string">&quot;applicationContext.xml&quot;</span>);</span><br><span class="line">		<span class="comment">// 获得JmsTemplate</span></span><br><span class="line">		JmsTemplate jmsTemplate = applicationContext.getBean(JmsTemplate.class);</span><br><span class="line">		<span class="comment">// 获得Destination</span></span><br><span class="line">		ActiveMQQueue queue = applicationContext.getBean(ActiveMQQueue.class);</span><br><span class="line">		<span class="comment">// 发送消息</span></span><br><span class="line">		jmsTemplate.send(queue, <span class="keyword">new</span> MessageCreator() &#123;</span><br><span class="line">			</span><br><span class="line">			<span class="meta">@Override</span></span><br><span class="line">			<span class="function"><span class="keyword">public</span> Message <span class="title">createMessage</span><span class="params">(Session session)</span> <span class="keyword">throws</span> JMSException </span>&#123;</span><br><span class="line">				<span class="keyword">return</span> session.createTextMessage(<span class="string">&quot;send-spring&quot;</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h4 id="4-配置消费者"><a href="#4-配置消费者" class="headerlink" title="4.配置消费者"></a>4.配置消费者</h4><p>&nbsp;&nbsp;Spring通过MessageListenerContainer接收信息,并把接收到的信息分发给MessageListener进行处理。每个消费者对应每个目的地都需要有对应的MessageListenerContainer。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- ActiveMQ提供的ConnectionFactory --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;targetConnectionFactory&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;</span>&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;brokerURL&quot;</span> value=<span class="string">&quot;tcp://192.168.145.137:61616&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!-- Spring的ConnectionFactory需要注入ActiveMQ的ConnectionFactory --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;connectionFactory&quot;</span></span><br><span class="line">	<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.springframework.jms.connection.SingleConnectionFactory&quot;</span>&gt;</span><br><span class="line">	&lt;!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;targetConnectionFactory&quot;</span> ref=<span class="string">&quot;targetConnectionFactory&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">   &lt;!-- 配置生产者 --&gt;</span><br><span class="line">&lt;!-- Spring提供的JMS工具类，它可以进行消息发送、接收等 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;jmsTemplate&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.springframework.jms.core.JmsTemplate&quot;</span>&gt;</span><br><span class="line">	&lt;!-- 注入Spring的连接工厂 --&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;connectionFactory&quot;</span> ref=<span class="string">&quot;connectionFactory&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!--P2P模式的Destination --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;queueDestination&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.command.ActiveMQQueue&quot;</span>&gt;</span><br><span class="line">	&lt;constructor-arg&gt;</span><br><span class="line">		&lt;value&gt;queue&lt;/value&gt;</span><br><span class="line">	&lt;/constructor-arg&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!-- publish/subscribe模式的Destination --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;topicDestination&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.apache.activemq.command.ActiveMQTopic&quot;</span>&gt;</span><br><span class="line">	&lt;constructor-arg value=<span class="string">&quot;topic&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;!-- 配置监听器 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;myMessageListener&quot;</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;com.activemq.MyMessageListener&quot;</span> /&gt;</span><br><span class="line">&lt;!-- 消息监听容器 --&gt;</span><br><span class="line">&lt;bean id=<span class="string">&quot;jmsContainer&quot;</span></span><br><span class="line">	<span class="class"><span class="keyword">class</span></span>=<span class="string">&quot;org.springframework.jms.listener.DefaultMessageListenerContainer&quot;</span>&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;connectionFactory&quot;</span> ref=<span class="string">&quot;connectionFactory&quot;</span> /&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;destination&quot;</span> ref=<span class="string">&quot;queueDestination&quot;</span> /&gt;</span><br><span class="line">	&lt;property name=<span class="string">&quot;messageListener&quot;</span> ref=<span class="string">&quot;myMessageListener&quot;</span> /&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure>
<p>监听器需要实现MessageListener接口。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyMessageListener</span> <span class="keyword">implements</span> <span class="title">MessageListener</span> </span>&#123;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onMessage</span><span class="params">(Message message)</span> </span>&#123;</span><br><span class="line">		System.out.println(message);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Exception"><a href="#Exception" class="headerlink" title="Exception"></a>Exception</h3><p>&nbsp;&nbsp;启动ActiveMQ时,如果发生java.net.UnknownHostException异常。<br>解决方法:<br>修改 /etc/hosts 文件 添加一行 192.168.1.1(主机IP) 主机名.localdomain 主机名<br>例: 192.168.145.137 ActiveMQ.localdomain ActiveMQ</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/yuwanzi.io/tags/ActiveMQ/" rel="tag"># ActiveMQ</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/06/30/2016-06-30-solrcloud/" rel="prev" title="SolrCloud初体验">
                  <i class="fa fa-chevron-left"></i> SolrCloud初体验
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/yuwanzi.io/2016/07/09/2016-07-09-MyCat/" rel="next" title="MyCat快速入门">
                  MyCat快速入门 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">玉丸子</span>
</div>
  <div class="powered-by">Erstellt mit  <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a>
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/yuwanzi.io/js/utils.js"></script><script src="/yuwanzi.io/js/motion.js"></script><script src="/yuwanzi.io/js/schemes/muse.js"></script><script src="/yuwanzi.io/js/next-boot.js"></script>

  






  





</body>
</html>
